package com.sheng.leetcode.year2022.month09.day29;

import org.junit.Test;

/**
 * @author liusheng
 * @date 2022/09/29
 *<p>
 * 面试题 01.09. 字符串轮转<p>
 *<p>
 * 字符串轮转。给定两个字符串s1和s2，请编写代码检查s2是否为s1旋转而成<p>
 * （比如，waterbottle是erbottlewat旋转后的字符串）。<p>
 *<p>
 * 示例1:<p>
 *  输入：s1 = "waterbottle", s2 = "erbottlewat"<p>
 *  输出：True<p>
 *<p>
 * 示例2:<p>
 *  输入：s1 = "aa", s2 = "aba"<p>
 *  输出：False<p>
 *<p>
 * 提示：<p>
 * 字符串长度在[0, 100000]范围内。<p>
 *<p>
 * 说明:<p>
 * 你能只调用一次检查子串的方法吗？<p>
 *<p>
 * 来源：力扣（LeetCode）<p>
 * 链接：<a href="https://leetcode.cn/problems/string-rotation-lcci">...</a><p>
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。<p>
 */
public class LeetCodeIsFlipedString {

    @Test
    public void test01() {
//        String s1 = "waterbottle", s2 = "erbottlewat";
//        String s1 = "aa", s2 = "aba";
        String s1 = "PvcvpkpHwaXQxpgGzURBvHRMvCsCPPmlKBSzXDWSvrxLBPdAvRpgcIwNOVQDdwPIElrAFqmb", s2 = "SvrxLBPdAvRpgcIwNOVQDdwPIElrAFqmbPvcvpkpHwaXQxpgGzURBvHRMvCsCPPmlKBSzXDW";
        System.out.println(new Solution().isFlipedString(s1, s2));
    }
}
class Solution {
    public boolean isFlipedString(String s1, String s2) {
        if (s1.length() != s2.length()) {
            return false;
        }
        char[] c1 = s1.toCharArray();
        char[] c2 = s2.toCharArray();
        int index = 0;
        // 找到s2字符串中的第一个字符在s1字符串中对应的索引
        for (int i = 0; i < s2.length(); i++) {
            // 如果在c2中找到和c1的第一个相等的字符，并且其后的字符串也相等时
            if (c1[index] == c2[i] && s1.substring(0, s2.length() - i).equals(s2.substring(i))) {
                index = s2.length() - i;
                break;
            }
        }
        for (int i = index, j = 0; i < s2.length(); i++, j++) {
            if (c1[i] != c2[j]) {
                return false;
            }
        }
        return true;
    }
}
